package com.qf.shop.sms.listener;

import com.qf.shop.common.constants.RabbitMQCons;
import com.qf.shop.common.pool.ShopExcutors;
import com.qf.shop.common.vo.SmsVo;
import com.qf.shop.sms.utils.HttpUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SendSms {

    @Value("${sms.host}")
    private String host;

    @Value("${sms.path}")
    private String path;

    @Value("${sms.appCode}")
    private String appCode;

    @Value("${sms.method}")
    private String method;

    @RabbitListener(queues = RabbitMQCons.SMS_QUEUE)
    public void send(SmsVo smsVo, Channel channel, Message message) {
        ShopExcutors.getExecutor().submit(()->{
            log.debug("smsVO:{}", smsVo);
            // 1.创建一个Map用来封装发送短信的信息
            Map<String, String> headers = new HashMap<String, String>();

            // 2.把信息全封装到Map中
            headers.put("Authorization", "APPCODE " + appCode);
            Map<String, String> querys = new HashMap<String, String>();
            querys.put("mobile", smsVo.getPhone());
            querys.put("templateId", smsVo.getTempId());
            querys.put("value", smsVo.getCode());
            try {
                // 3.发送短信
                // HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, new HashMap<String, String>());

                // 4.解析响应的内容
                // log.debug("resp:{}", EntityUtils.toString(response.getEntity(), "utf-8"));
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("MQ ACK 异常", e);
            } catch (Exception e) {
                log.error("发送短信失败", e);
            }
        });


    }
}
